import 'package:flutter/material.dart';

class ShakeWidget extends StatelessWidget {
  const ShakeWidget({
    Key? key,
    this.duration = const Duration(milliseconds: 300),
    this.deltaX = 20,
    this.curve = Curves.bounceOut,
    required this.child,
    this.vibration = 0.25,
  }) : super(key: key);

  final Duration duration;
  final double deltaX;
  final Widget child;
  final Curve curve;
  final double vibration;

  /// convert 0-1 to 0-1-0
  double shake(double a) {
    const double k = 7;
    double _d;

    if (a <= 1 / 7) {
      _d = -k * a;
    } else if (a <= 3 / 7) {
      _d = k * a - 2;
    } else if (a <= 9 / 14) {
      _d = -k * a + 4;
    } else if (a <= 11 / 14) {
      _d = k * a - 5;
    } else if (a <= 12.5 / 14) {
      _d = -k * a + 5.5;
    } else if (a <= 13.5 / 14) {
      _d = k * a - 6;
    } else {
      _d = -k * a + 7;
    }

    return _d * vibration;
  }

  @override
  Widget build(BuildContext context) {
    return TweenAnimationBuilder<double>(
      key: key,
      tween: Tween<double>(begin: 0.0, end: 1.0),
      duration: duration,
      builder: (BuildContext context, double animation, Widget? child) =>
          Transform.translate(
        offset: Offset(deltaX * shake(animation), 0),
        child: child,
      ),
      child: child,
    );
  }
}
